//
//  GetIdentifyingViewController.m
//  Consume100
//
//  Created by eliot on 16/3/21.
//  Copyright © 2016年 aleven. All rights reserved.
//

#import "GetIdentifyingViewController.h"
#import "GetBackPassWordViewController.h"
@interface GetIdentifyingViewController ()

/** 设置定时器*/
@property (nonatomic, strong) NSTimer *timer;

@property (weak, nonatomic) IBOutlet UIButton *nextBtn;

@property (weak, nonatomic) IBOutlet UIButton *getIdentifyingBtn;

@property (weak, nonatomic) IBOutlet UILabel *getPassWordLb;

@property (weak, nonatomic) IBOutlet UITextField *inputIdentifyingTextField;
@property (nonatomic) int time;

@property (nonatomic, strong) NSString *gotIdentifing;


@end

@implementation GetIdentifyingViewController

- (void)viewWillAppear:(BOOL)animated {
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
}


+(GetIdentifyingViewController*)CreatGetIdentifyingViewController{
    
    UIStoryboard *story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    GetIdentifyingViewController *identifying=[story instantiateViewControllerWithIdentifier:@"GetIdentifyingViewController"];
    return identifying;
}


- (IBAction)clickNextBtn:(id)sender {

    //1.检查验证码是否过期
    NSData *encodeData = [[NSUserDefaults standardUserDefaults] objectForKey:@"userModel"];
    UserModel *model = [NSKeyedUnarchiver unarchiveObjectWithData:encodeData];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 5;
    NSDictionary *dic = @{@"code":self.inputIdentifyingTextField.text,@"type":@"1",@"phone":model.phone};
    NSString *baseUrl = [NSString stringWithFormat:@"%@checkCode.jhtml", MyBaseURL];
    [manager POST:baseUrl parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSString *errorCode = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@,errorCode=%@", dic, errorCode);
        if ([errorCode isEqualToString:@"forgetPwdCodeTimeOut"]) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUD];
                [MBProgressHUD showError:@"验证码已过期，请重新获取"];
            });
        }
        if ([errorCode isEqualToString:@"checkPwdCodeFail"]) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUD];
                [MBProgressHUD showError:@"验证码错误"];
            });
        }
        if ([errorCode isEqualToString:@"checkPwdCodeFail"]) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUD];
                [MBProgressHUD showError:@"验证码错误"];
            });
        }
        if ([errorCode isEqualToString:@"checkPwdCodeSuccess"]) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                GetBackPassWordViewController *vc = [GetBackPassWordViewController CreatGetBackPassWordViewController];
                vc.viewTitle = self.viewTitle;
                [self creatNav:vc];
            });
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:@"链接超时,请检查网络"];
        });
    }];
}
//创建模态导航控制器
-(void)creatNav:(UIViewController *)view{
    
    UINavigationController *nav=[[UINavigationController alloc] initWithRootViewController:view];
    nav.navigationBar.barTintColor = [UIColor colorWithRed:254/255.0 green:154/255.0 blue:37/255.0 alpha:1];
    view.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_back"] style:UIBarButtonItemStylePlain target:self action:@selector(dismiss)];
    [self presentViewController:nav animated:YES completion:nil];
}

- (void)dismiss {
    [self dismissViewControllerAnimated:YES completion:nil];
}

//页面消失，进入后台不显示该页面，关闭定时器
-(void)viewDidDisappear:(BOOL)animated
{
    //关闭定时器
    [self.timer setFireDate:[NSDate distantFuture]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSData *encodeData = [[NSUserDefaults standardUserDefaults] objectForKey:@"userModel"];
    UserModel *model = [NSKeyedUnarchiver unarchiveObjectWithData:encodeData];
    
    
    
    self.getPassWordLb.text = [NSString stringWithFormat:@"验证码已经发送到%@", model.phone];
    
    
    self.nextBtn.layer.cornerRadius = 4;
    self.nextBtn.layer.masksToBounds = YES;
    self.getIdentifyingBtn.layer.cornerRadius = 4;
    self.getIdentifyingBtn.layer.masksToBounds = YES;
    self.nextBtn.backgroundColor = [UIColor colorWithRed:255/255.0 green:88/255.0 blue:88/255.0 alpha:1];
    self.getIdentifyingBtn.backgroundColor = [UIColor colorWithRed:255/255.0 green:88/255.0 blue:88/255.0 alpha:1];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:19],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    self.view.backgroundColor = [UIColor colorWithRed:237/255.0 green:237/255.0 blue:237/255.0 alpha:1];
    self.inputIdentifyingTextField.keyboardType = UIKeyboardTypeNumberPad;
    self.title = self.viewTitle;
    
    /** 设置导航啦样式*/
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:19],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
    self.navigationController.navigationBar.translucent = NO;
    self.time = 60;
   
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timeToPostIdentifyAgagin:) userInfo:nil  repeats:YES];
    self.getIdentifyingBtn.userInteractionEnabled = NO;
    self.getIdentifyingBtn.backgroundColor = [UIColor grayColor];
    //开启定时器
    [self.timer setFireDate:[NSDate distantPast]];
    self.getIdentifyingBtn.titleLabel.font = [UIFont systemFontOfSize:10];
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 5;
    NSDictionary *dic = @{@"type":@"2"};
    NSString *baseUrl = [NSString stringWithFormat:@"%@sendMsg.jhtml", MyBaseURL];
    [manager POST:baseUrl parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:@"链接超时,请检查网络"];
        });
    }];
}



- (void)timeToPostIdentifyAgagin:(int)time {
    if (self.time > 0 ) {
        self.time -= 1;
        [self.getIdentifyingBtn setTitle:[NSString stringWithFormat:@"%dS重新获取验证码", self.time] forState:UIControlStateNormal];
        
    }else {
        
        //关闭定时器
        [self.timer setFireDate:[NSDate distantFuture]];
        self.time = 60;
        [self.getIdentifyingBtn setTitle:@"重新获取验证码"forState:UIControlStateNormal];
        self.getIdentifyingBtn.backgroundColor = [UIColor colorWithRed:254/255.0 green:154/255.0 blue:37/255.0 alpha:1];
        self.getIdentifyingBtn.userInteractionEnabled = YES;
    }
    
    
}

/** 获取验证码*/
- (IBAction)getIdentifing:(id)sender {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 5;
    NSDictionary *dic = @{@"type":@"2"};
    NSString *baseUrl = [NSString stringWithFormat:@"%@sendMsg.jhtml", MyBaseURL];
    [manager POST:baseUrl parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:@"链接超时,请检查网络"];
        });
    }];
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
